package com.bee.bootstrap.role.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.bee.bootstrap.role.entity.Role;
import com.bee.bootstrap.role.service.IRoleService;
import com.bee.common.core.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liekkas
 * @since 2018-05-25
 */
@RestController
@RequestMapping("/roles")
@Api(value = "/roles", description = "角色管理")
public class RoleController {

    @Autowired
    private IRoleService roleServiceImpl;

    @GetMapping
    @ApiOperation(value="获取角色列表分页")
    public Result readRoles(@ModelAttribute Role role, Page<Role> page){
        return roleServiceImpl.findPageView(page,role);
    }

    @GetMapping("/{id}/resources")
    @ApiOperation(value="获取角色资源")
    public Result readRoles(@PathVariable(required = true,value ="id") long id){
        return roleServiceImpl.findRoleResources(id);
    }

    @PostMapping("/{id}/resources")
    @ApiOperation(value="保存角色资源")
    public Result readRoles(@PathVariable(required = true,value ="id") long id,@RequestBody Role role){
        return roleServiceImpl.addRoleResources(id,role);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除角色")
    public Result deleteRole(@PathVariable(required = true,value ="id") long id){
        return roleServiceImpl.deleteRoleById(id);
    }

    @PutMapping("/{id}")
    public Result updateRole(@Valid @RequestBody Role role, @PathVariable(required = true,value ="id") long id,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return roleServiceImpl.updateRole(role);
    }

    @PostMapping("")
    public Result createRole(@Valid @RequestBody Role role,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return roleServiceImpl.insertRole(role);
    }
	
}
